package com.sinven.service;

import com.sinven.common.ActionResult;
import com.sinven.common.Pager;
import com.sinven.mapper.TeacherMapper;
import com.sinven.pojo.Teacher;
import com.sinven.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TeacherServiceImpl implements TeacherService{
    @Autowired
    private TeacherMapper teacherMapper;
    @Override
    public ActionResult<List<Teacher>> queryCurPageData(Integer curpage, Integer pageSize) {
        //得到总记录数
        long totalRecords = teacherMapper.countTeachers();
        if (totalRecords == 0) {
            return ResultUtil.success(null);
        }

        //this.totalRecord = totalRecord;
        //如果pageSize没有传递 或者不合法(小于1)
        if(pageSize == null || pageSize <0 ){
           pageSize = 5;
        }
        //给curPage赋值
        if(curpage == null || curpage<0){
            curpage = 1;
        }
        //计算总页数
        long totalPage = totalRecords % pageSize == 0?
                totalRecords / pageSize :
                totalRecords / pageSize +1;
        //防止页面恶意传值 超出部分直接显示为最后一页
        if(curpage > totalPage){
            curpage = (int)totalPage;
        }
        long startIndex = (curpage - 1) * pageSize;
        List<Teacher> teachers = teacherMapper.queryAll(startIndex, pageSize);
        return ResultUtil.success(totalRecords,teachers);
    }

    @Override
    public Teacher getTeacherByTid(long tid) {
        return teacherMapper.queryTeacherByTid(tid);
    }

    @Override
    public boolean addTeacher(Teacher teacher) {
        return teacherMapper.addTeacher(teacher) > 0;
    }

    @Override
    public boolean updateTeacher(Teacher teacher) {
        return teacherMapper.updateTeacher(teacher) > 0 ;
    }

    @Override
    public boolean deleteTeacher(long tid) {
        return teacherMapper.deleteTeacher(tid) > 0 ;
    }

    @Override
    public Pager<Teacher> queryCurPageData(Long curPage) {
        //得到总记录数
        long totalRecords = teacherMapper.countTeachers();
        if(totalRecords <= 0){
            return null;
        }
        Pager<Teacher> pager = new Pager(totalRecords,curPage,5);
        List<Teacher> teachers = teacherMapper.queryAll(pager.getStartIndex(), pager.getPageSize());
        pager.setDatas(teachers);
        return pager;
    }


}
